package leetcode100;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class lc059 {

    /**
     * per..ties [0] 需要先修[1]
     * 作[1] 对应的List包括[0]...
     * 寻找没有先修课的课indegree==0
     * 寻找每门课修完后续需要修什么课
     * 修完一门无门槛课,  再去更新后修课, 看看当前有没有有无门槛课
     * 如果修完的课 等于 要修的课, 无循环依赖
     *
     * @param numCourses
     * @param prerequisites
     * @return
     */

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        List<List<Integer>> adj = new ArrayList<>(numCourses);
        for (int i = 0; i < numCourses; i++) {
            adj.add(new ArrayList<>());
        }

        int[] indegree = new int[numCourses];
        for (int[] prerequisite : prerequisites) {
            adj.get(prerequisite[1]).add(prerequisite[0]);
            indegree[prerequisite[0]]++;
        }

        LinkedList<Integer> queue = new LinkedList<>();
        for (int i = 0; i < indegree.length; i++) {
            if (indegree[i]==0) {
                queue.offer(i);
            }
        }

        int count = 0;
        while (!queue.isEmpty()) {
            int curr = queue.poll();
            count++;
            for (int course : adj.get(curr)) {
                indegree[course]--;
                if (indegree[course] == 0) {
                    queue.offer(course);
                }
            }
        }
        return count==numCourses;
    }

}
